"use strict";
const BasicController = require("./basic");
const svgCaptcha = require("svg-captcha");
const fse = require("fs-extra");
const path = require("path");
class UtilController extends BasicController {
      async captcha() {
            const captcha = svgCaptcha.create({
                  size: 4,
                  fontSize: 50,
                  width: 100,
                  height: 40,
                  noise: 3,
            });

            this.ctx.session.captcha = captcha.text;
            this.ctx.response.type = "image/svg+xml";
            this.ctx.body = captcha.data;
      }

      async sendEmailCode() {
            let { ctx, service } = this;
            let email = ctx.query.email;

            // 生成随机验证码
            const emailCode = String(Math.random()).substring(3, 9);
            // 保存随机验证码到session里
            ctx.session.emailCode = emailCode;

            // 编写邮件格式，后期可以尝试模板
            const subject = "胖子验证码";
            const text = "";
            const html = `<h1>给胖子送来的验证码</h1><stroge>验证码：${emailCode}</stroge>`;

            // 发送邮件
            const { message, success } = await service.tools.sendMail(
                  email,
                  subject,
                  text,
                  html
            );

            if (success) {
                  return this.message(message);
            }

            this.error("发送失败", message);
      }

      async mergeFile() {
            let { ext, size, hash } = this.ctx.request.body;
            const filePath = path.resolve(
                  this.config.UPLOAD_DIR,
                  `${hash}.${ext}`
            );
            await this.ctx.service.tools.mergeFile(filePath, hash, size);
            this.success({ url: `/public/${hash}.${ext}` });
      }

      async checkFile() {
            let { hash, ext } = this.ctx.request.body;
            const filePath = path.resolve(
                  this.config.UPLOAD_DIR,
                  `${hash}.${ext}`
            );

            let uploaded = false;
            let uploadedList = [];
            if (fse.existsSync(filePath)) {
                  //文件存在
                  uploaded = true;
            } else {
                  uploadedList = await this.getUploadedList(hash);
            }

            this.success({ uploaded, uploadedList });
      }

      async getUploadedList(hash) {
            const dirPath = path.resolve(this.config.UPLOAD_DIR, hash);
            if (fse.existsSync(dirPath)) {
                  const hasHashDirList = await fse.readdir(dirPath);
                  return hasHashDirList.filter(
                        (dir) => dir.split("-").shift() === hash
                  );
            }
            return [];
      }

      async uploadFile() {
            // 模拟测试错误情况
            // if (Math.random() > 0.2) {
            //       this.ctx.status = 500;
            //       return;
            // }
            let { ctx } = this;
            const { fileName, hash } = ctx.request.body;
            const file = ctx.request.files[0];
            const chunkPath = path.resolve(this.config.UPLOAD_DIR, hash);
            if (!fse.existsSync(chunkPath)) {
                  fse.mkdirSync(chunkPath);
            }

            await fse.move(file.filepath, `${chunkPath}/${fileName}`);
            this.message("切片上传成功");
      }
}

module.exports = UtilController;
